package com.trkj.taoruiyun;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTabHost;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewConfiguration;
import android.widget.TabHost;
import android.widget.TabWidget;
import android.widget.TextView;

import com.trkj.base.AppManager;
import com.trkj.base.BaseFragmentActivity;
import com.trkj.base.Constants;
import com.trkj.base.utils.AndroidSystem;
import com.trkj.push.Push;
import com.trkj.share.SearchActivity;
import com.trkj.usercenter.ApiActivity;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;


public class MainActivity extends BaseFragmentActivity {
    public static final String ACTION = "android.intent.action.MAIN";

    private FragmentTabHost tabHost;

    private int[] tabItemIcons = {
            R.string.fa_align_justify,
            R.string.fa_share_alt,
            R.string.fa_cloud_download,
            R.string.fa_ellipsis_h
    };
    private String[] tabItemTexts = {
            "考与练",
            "技术分享",
            "资料下载",
            "更多"
    };

    private Fragment[] fragments = {
            new ExamFragment(),
            new ShareFragment(),
            new DocumentDownloadFragment(),
            new MyFragment()
    };

    private Map<String, Intent> intents;

    private Push push;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        initTabWeiget();
        initIntent();
        forceShowOverflowMenu();

        push = new Push(this);
        push.startPush();
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_main, menu);
        //menu.findItem(R.id.menu_api).setIcon(FontIconDrawable.inflate(this, R.xml.icon_star));
        //menu.findItem(R.id.menu_search).setIcon(FontIconDrawable.inflate(this, R.xml.icon_search));
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        Intent intent = null;
        switch(id){
            case R.id.menu_api:
                intent = intents.get(Constants.Intent.INTENT_ACTIVITY_API);
                startActivity(intent);
                break;
            case R.id.menu_exit:
                AppManager.getAppManager().AppExit(this);
                break;
            case R.id.menu_search:
                intent = new Intent(SearchActivity.ACTION);
                startActivity(intent);
                break;
            case R.id.menu_upgrage:
                AndroidSystem.checkUpgrade(this);
                break;
        }

        return super.onOptionsItemSelected(item);
    }

    protected void initIntent(){
        intents = new HashMap<String, Intent>();
        intents.put(Constants.Intent.INTENT_ACTIVITY_API, new Intent(ApiActivity.ACTION));
    }

    /**
     * 创建选项卡按钮
     *
     * @param idx 按钮索引
     * @return 返回新的选项卡标签
     */
    protected View createTabItem(int idx) {
        LayoutInflater inflater = LayoutInflater.from(this);
        View tabItemLayout = inflater.inflate(R.layout.tab_item, null);

        TextView tabItemIcon = (TextView) tabItemLayout.findViewById(R.id.tab_item_icon);
        Constants.Font.setAwesomeFont(this, tabItemIcon);
        tabItemIcon.setText(Constants.ResString.getString(this, tabItemIcons[idx]));

        TextView tabItemText = (TextView) tabItemLayout.findViewById(R.id.tab_item_text);

        tabItemText.setText(tabItemTexts[idx]);

        return tabItemLayout;
    }

    /**
     * 初始化底部选项卡
     */
    protected void initTabWeiget() {
        tabHost =
                (FragmentTabHost) this.findViewById(android.R.id.tabhost);
        tabHost.setup(this, this.getSupportFragmentManager(), R.id.realcontent);

        for (int i = 0; i < fragments.length; i++) {
            tabHost.addTab(
                    tabHost.newTabSpec(tabItemTexts[i])
                            .setIndicator(this.createTabItem(i)),
                    fragments[i].getClass(),
                    null
            );
        }
        tabHost.getTabWidget().setBackgroundResource(R.drawable.tab_widget_top_line);
        tabHost.getTabWidget().setDividerDrawable(null);

        //设置选项卡切换的监听器
        OnTaoRuiYunTabChangeListener tabChangeListener = new OnTaoRuiYunTabChangeListener();
        tabHost.setOnTabChangedListener(tabChangeListener);
        //将第0个选项卡的颜色设置为选中颜色
        tabChangeListener.setTabItemTextColor(0, Constants.Color.getColor(this, R.color.normal_selected));
    }

    /**
     * 底栏选项卡切换监听器，用于改变文字颜色
     */
    class OnTaoRuiYunTabChangeListener implements TabHost.OnTabChangeListener{
        @Override
        public void onTabChanged(String tabId) {
            TabWidget tabWidget = tabHost.getTabWidget();

            for(int i = 0; i < tabWidget.getTabCount(); i ++){
                if(tabHost.getCurrentTab() == i){
                    if(i == 3){
                        ((TextView) getActionBar().getCustomView()).setText("");
                    }else {
                        ((TextView) getActionBar().getCustomView()).setText(tabItemTexts[i]);
                    }
                    setTabItemTextColor(i, Constants.Color.getColor(MainActivity.this, R.color.normal_selected));
                }else{
                    setTabItemTextColor(i, Constants.Color.getColor(MainActivity.this, R.color.normal_unselected));
                }
            }
        }

        /**
         * 设置第currentTabIndex个选项卡的文字颜色为color
         * @param currentTabIndex 选项卡索引
         * @param colorId 颜色
         */
        public void setTabItemTextColor(int currentTabIndex, int colorId){
            TabWidget tabWidget = tabHost.getTabWidget();
            View currentTab =  tabWidget.getChildTabViewAt(currentTabIndex);
            TextView tabItemText = (TextView) currentTab
                    .findViewById(R.id.tab_item_text);
            TextView tabItemIcon = (TextView) currentTab.findViewById(R.id.tab_item_icon);
            tabItemText.setTextColor(colorId);
            tabItemIcon.setTextColor(colorId);
        }
    }

    @Override
    protected String getCenterTitle() {
        return tabItemTexts[0];
    }

    /**
     * 强制显示overflow按钮
     */
    private void forceShowOverflowMenu() {
        try {
            ViewConfiguration config = ViewConfiguration.get(this);
            Field menuKeyField = ViewConfiguration.class
                    .getDeclaredField("sHasPermanentMenuKey");
            if (menuKeyField != null) {
                menuKeyField.setAccessible(true);
                menuKeyField.setBoolean(config, false);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 清除数据（重新登录时用）
     */
    public void clearSubFragmentData(){
        //清除考试与练习数据
        ExamFragment examFragment = (ExamFragment) getSupportFragmentManager()
                .findFragmentByTag(tabItemTexts[0]);
        if(examFragment != null) {
            examFragment.clearSubFragmentData();
        }

        //清除资料下载数据
        //第一次启动该Fragment可能还没有创建哦，所以要判断一下是否为null
        DocumentDownloadFragment downloadFragment
                = (DocumentDownloadFragment)getSupportFragmentManager()
                .findFragmentByTag(tabItemTexts[2]);
        if(downloadFragment != null) {
            downloadFragment.clear();
        }
    }
}
